/**
 * Created by Tuffy on 2017/1/3.
 */
'use strict';

var express = require('express');
var router = express.Router();

var request = require('request');
var xlsx = require('node-xlsx');
var _ = require('underscore');

var fs = require('fs');
var urlPath = require('url');
var nodeExcel = require('excel-export');

var baseConfig = require('./resource/base-config');
var sessionUtils = require('./utils/session-utils');
var distributionService = require('./service/distribution-sevice');
var adminHost = 'adminHost';
var tmsdriverHost = 'tmsdriverHost';

/**
 *
 */
router.get('/excel', function (req, res, next) {
    request.get({
        url: baseConfig[adminHost] + '/' + req.query.url + '?' + parseUrl(req),
        headers: {
            'Authorization': sessionUtils.getToken(req)
        }
    }, function (err, response, body) {
        if (!err) {
            var result = JSON.parse(body);
            if (result.success) {
                var rtnData = result.data;
                var data = [rtnData.title];
                _.map(rtnData.list, function (item) {
                    data.push(item);
                });
                var name = rtnData.name;
                var buffer = xlsx.build([{name: name, data: data}]);
                res.setHeader('Content-Type', 'application/vnd.ms-excel');
                res.setHeader('Content-Disposition', 'attachment; filename=' + encodeURIComponent(name) + '.xlsx');
                res.end(buffer);
            }
        }
    });
});
router.get('/exportExcel', function (req, res, next) {
    var confs = [];
    var conf = {};
    conf.cols = [{
        caption: '司机姓名',
        type: 'string'
    },
        {
            caption: '手机号',
            type: 'string'
        },
        {
            caption: '排队序号',
            type: 'number'
        },
        {
            caption: '驾照信息',
            type: 'string'
        },
        {
            caption: '意向路线',
            type: 'string'
        },
        {
            caption: '排队时间',
            type: 'string'
        }];
    distributionService.exportExcel(req, res, function (result) {
        if (result.success) {
            var rs = result.data;
            var lists = new Array();
            if (rs.length > 0) {
                for (var i=0; i < rs.length; i++) {
                    var list = new Array();
                    list.push(rs[i].name, rs[i].phone, rs[i].queue, rs[i].license, rs[i].purpose, rs[i].queueTime);
                    lists.push(list);
                }
            }
            console.log(lists);
            conf.rows = lists;
            for (var i = 0; i < 1; i++) {
                conf = JSON.parse(JSON.stringify(conf));   //clone
                conf.name = 'sheet' + i;
                confs.push(conf);
            }
            var result = nodeExcel.execute(confs);
            res.setHeader('Content-Type', 'application/vnd.openxmlformats');
            res.setHeader("Content-Disposition", "attachment; filename=" + "queueDriver.xlsx");
            res.end(result, 'binary');
        }
    });
});

/**
 * 解析url参数
 * @param req 请求
 * @returns {string}
 */
function parseUrl(req) {
    var urlArray = [];
    for (var i in req.query) {
        if (i !== 'url') {
            urlArray.push(i + '=' + req.query[i]);
        }
    }
    return urlArray.join('&');
}

module.exports = router;